package com.example.bicycle.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.bicycle.domain.entity.User;
import com.example.bicycle.domain.enums.UserTypeEnum;
import com.example.bicycle.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@SaCheckLogin
@RestController
@RequestMapping("/bicycle/")
public class RegisterController {
    private final UserService userService;

    @Autowired
    public RegisterController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("doRegister")
    public SaResult doRegister(@RequestBody User user) {
        try {
            /* 先判断用户名是否重复 */
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", user.getUsername());
            User existingUser = userService.getOne(queryWrapper);
            
            if (existingUser != null) {
                return SaResult.error("用户名已存在，请选择其他用户名");
            }
            
            /* 默认user为普通用户 */
            user.setUserType(UserTypeEnum.NORMAL);
            user.setCreatedAt(new Date());
            
            boolean saved = userService.save(user);
            if (saved) {
                return SaResult.ok("注册用户成功,正在跳转登录页面");
            } else {
                return SaResult.error("注册失败，请稍后再试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return SaResult.error("注册失败：" + e.getMessage());
        }
    }
}
